package com.java.json;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.*;

/**
 * @author wangning
 * @create 2021-10-14 10:37
 */
public class FastJSONToMapTest {
	public static void main(String[] args) {
//		String str = "{\"item1\":\"000000\",\"company_id\":\"010026606\",\"data\":[{\"contract_no\":\"15.000\",\"end_date\":\"201403\",\"no\":\"1\",\"field1\":\"201403\",\"balance\":\"400\",\"late_fee\":\"0\",\"pay_amount\":\"6000\",\"begin_date\":\"201403\",\"customer_name\":\"武圣西里 5 楼 3 门 601\"}],\"ceb_track\":\"20200902217114715579\",\"bill_key\":\"050405543\",\"total_num\":\"1\",\"inst_id\":\"100000000000217\",\"item3\":\"60.00\"}";
		String str = "[{\"title\":\"使用情况\",\"options\":[{\"name\":\"好\",\"value\":1},{\"name\":\"不好\",\"value\":2},{\"name\":\"还行\",\"value\":3}]},{\"title\":\"优化情况\",\"options\":[{\"name\":\"好\",\"value\":1},{\"name\":\"不好\",\"value\":2},{\"name\":\"还行\",\"value\":3}]}]";
		List<HashMap> list = JSON.parseArray(str, HashMap.class);
		System.out.println("list = " + list);
		for(HashMap configData : list ){//这行出错,com.java.json.FastJSONToMapTest.main(FastJSONToMapTest.java:20)
			System.out.println("configData = " + configData);

//			System.out.println(configData.get("options"));
			HashMap<String, Object> stringObjectHashMap = fromJson2Map(JSON.toJSONString(configData));
			System.out.println("stringObjectHashMap = " + stringObjectHashMap);
			System.out.println(stringObjectHashMap.get("options"));
			List options = (ArrayList<HashMap>) stringObjectHashMap.get("options");
			System.out.println(((HashMap)options.get(0)).get("value"));
		}

//		HashMap<String, Object> stringObjectHashMap = fromJson2Map(str);
//		System.out.println(stringObjectHashMap);

	}

	// 将jsonString转化为hashmap
	private static HashMap<String, Object> fromJson2Map(String jsonString) {
		HashMap jsonMap = JSON.parseObject(jsonString, HashMap.class);
		HashMap<String, Object> resultMap = new HashMap<>();
		for (Object o : jsonMap.keySet()) {
			String key = (String) o;
			if (jsonMap.get(key) instanceof JSONArray) {
				JSONArray jsonArray = (JSONArray) jsonMap.get(key);
				List<HashMap<String, Object>> list = handleJSONArray(jsonArray);
				resultMap.put(key, list);
			} else {
				resultMap.put(key, jsonMap.get(key));
			}
		}
		return resultMap;
	}

	private static List<HashMap<String, Object>> handleJSONArray(JSONArray jsonArray) {
		List<HashMap<String, Object>> list = new ArrayList<>();
		for (Object object : jsonArray) {
			JSONObject jsonObject = (JSONObject) object;
			HashMap<String, Object> map = new HashMap<>();
			for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
				if (entry.getValue() instanceof JSONArray) {
					map.put(entry.getKey(), handleJSONArray((JSONArray) entry.getValue()));
				} else {
					map.put(entry.getKey(), entry.getValue());
				}
			}
			list.add(map);
		}
		return list;
	}
}
